import { cloneDeep, includes } from 'lodash-es'
import { http } from '@/utils/http'
import WS from '@/utils/ws.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDialogStore } from './dialog-store.js'
import _ from 'lodash-es'



export const useHomeStore = () => {
    const router = useRouter()
    const languageJson = inject('languageJson')
    const languageType = inject('languageType')
    const dialogstore = useDialogStore()
    const state = reactive({
        matchlistIntervalId: null,
        matchdetailIntervalId: null,

        activeleague: [],
        activesport: 'soccer',
        allleague: {
            loading: false,
            collapse: [],
            data: []
        },
        activecountryStyle: '',
        activematchtabs: 'all',
        matchtabs: {
            all: {
                label: languageJson?.value?.home?.all || '',
                count: 0
            },
            live: {
                label: languageJson?.value?.home?.realtime || '',
                count: 0
            },
            today: {
                label: languageJson?.value?.home?.today || '',
                count: 0
            },
            early: {
                label: languageJson?.value?.home?.earlier || '',
                count: 0
            },
        },
        match: {
            loading: false,
            data: [],
            page: 1,
            page_size: 10,
            total: 0
        },
        matchDetail: {
            show: false,
            loading: false,
            activetab: [
                "odds_data",
                "full"
            ],
            activeNames: [],
            tabs: [],
            primaryData: {},
            data: {},
            datas: {}
        },

        order: {
            activetype: 0,
            activeorderdata: [],
            data: {
                new_order_place_task_objs: [],
                live_order_place_task_objs: [],
                error_order_place_task_objs: []
            }
        },

        textmap: {
            soccer_handicap: {
                ce_odds_data: languageJson.value.home.corner,
                odds_data: '',
                pc_odds_data: languageJson.value.home.card,

                full: languageJson.value.home.full,
                half: languageJson.value.home.half,
                

                M: '',
                R: languageJson.value.home.letballgo,
                OU: languageJson.value.home.ou,
                OUH: languageJson.value.home.homeGoalTotal,
                OUC: languageJson.value.home.awayGoalTotal,
                CRS: ''
            },
            basketball_handicap: {
                ce_odds_data: languageJson.value.home.corner,
                odds_data: '',
                pc_odds_data: languageJson.value.home.card,
                // pd_odds_data: '波胆',

                full: languageJson.value.home.full,
                half: languageJson.value.home.half,

                section1: languageJson.value.home.section1,
                section2: languageJson.value.home.section2,

                M: '',
                R: languageJson.value.home.letballgo,
                OU: languageJson.value.home.ou,
                OUH: languageJson.value.home.basketballFirstScore,
                OUC: languageJson.value.home.basketballSecondScore,
                CRS: ''
            },
        }
    })

    const changeSport = (value) => {
        state.activesport = value
        initData()
    }

    const getallleague = () => {
        state.allleague.loading = true
        http.get(`/league/get_league_infos?sport_type=${state.activesport}&event_type=${state.activematchtabs}`).then((res) => {
            let a = []
            Object.values(res.data).forEach(value => {
                a.push(value)
            });
            state.allleague.loading = false
            state.allleague.data = a


        }).catch(() => {
            state.allleague.loading = false
        })
    }

    const getmatchcount = () => {
        let body = {
            sport_type: state.activesport,
            league_from: state.activeleague.length > 0 ? state.activeleague : 'all'
        }
        http.post(`/match/match_count`, body).then((res) => {
            state.matchtabs.all.count = res.data.all_count
            state.matchtabs.live.count = res.data.live_count
            state.matchtabs.today.count = res.data.today_count
            state.matchtabs.early.count = res.data.early_count

        })
    }

    const changeactivematchtabs = (key) => {
        state.activematchtabs = key
        state.match.data = []
        getallleague()
        getmatch(true)
    }

    const clickallleague = () => {
        state.matchDetail.show = false
        state.matchDetail.activetab = [
            "odds_data",
            "full"
        ]
        state.matchDetail.primaryData = {}
        state.matchDetail.data = {}
        state.matchDetail.datas = {}
        state.match.data = []
        state.activeleague = []
        state.activecountryStyle = ''
        getmatchcount()
        getallleague()
        getmatch(true)
    }

    const changeactiveleague = (value) => {
        state.matchDetail.show = false
        state.matchDetail.activetab = [
            "odds_data",
            "full"
        ]
        state.matchDetail.primaryData = {}
        state.matchDetail.data = {}
        state.matchDetail.datas = {}
        state.activecountryStyle = ''
        state.activeleague = [value]
        getmatchcount()
        getmatch(true)

        // state.activeleague = value
        // state.match.data = []
        // getmatch()
    }
    const changeactiveleague2 = (value) => {
        state.activecountryStyle = value
        let foundObject = state.allleague.data.find(item => item.country_id === value);
        let a = []
        Object.keys(foundObject.leagues).forEach(key => {
            a.push(foundObject.leagues[key].league_id
            )
        });
        state.activeleague = a
        getmatchcount()
        getmatch(true)

        // state.activeleague = value
        // state.match.data = []
        // getmatch()
    }

    const getmatch = (loading = true) => {
        if (loading) state.match.loading = true
        clearInterval(state.matchlistIntervalId)
        if (state.matchDetail.show == false) {
            let body = {
                platform_from: "hga",
                select_type_from: "event_type",
                event_type_from: state.activematchtabs,
                league_from: state.activeleague.length > 0 ? state.activeleague : 'all',
                page: state.match.page,
                page_size: state.match.page_size,
                sport_type_from: state.activesport
            }
            http.post('/match/match_select', body).then((res) => {
                state.match.loading = false
                state.match.data = res.data.match_list
                state.match.total = res.data.totle

                clearInterval(state.matchlistIntervalId)
                state.matchlistIntervalId = setInterval(() => getmatch(false), 3000)
            }).catch(() => {
                state.match.loading = false

                clearInterval(state.matchlistIntervalId)
                // state.matchlistIntervalId = setInterval(() => getmatch(false), 3000)
            })
        }

    }

    const openOrderDialog = () => {
        dialogstore.openNewDialog()


    }

    const clickmatch = (row) => {
        state.matchDetail.primaryData = JSON.parse(JSON.stringify(row))
        state.matchDetail.show = true
        state.matchDetail.loading = true

        getmatchdetail(row)
    }

    const getmatchdetail = (row) => {
        clearInterval(state.matchdetailIntervalId)
        if (state.matchDetail.show) {
            let body = {
                bc_type: "hga",
                event_type: row.event_type,
                match_id: row.match_id,
                ids: row.ids,
                sport_type: row.sport_type
            }

            http.post('/match/get_now_odds_all_details', body).then((res) => {
                state.matchDetail.loading = false
                state.matchDetail.data = res.data

                getmatchdetailDatas()
            }).catch(() => {
                state.matchDetail.loading = false
            })
        }


    }

    const changeDetailactivetab = (value) => {
        state.matchDetail.activetab = value
        state.matchDetail.activeNames = []

        Object.keys(state.matchDetail.data[state.matchDetail.activetab[0]][state.matchDetail.activetab[1]]).forEach(key => {
            state.matchDetail.activeNames.push(key)
        });
    }

    const getmatchdetailDatas = () => {
        let data = JSON.parse(JSON.stringify(state.matchDetail.data))
        let handicap = data.sport_type == "soccer" ? state.textmap.soccer_handicap : state.textmap.basketball_handicap

        let a = []
        Object.keys(data).forEach(key => {
            let value = data[key]
            Object.keys(value).forEach(key2 => {
                if (handicap[key] != null && handicap[key] != undefined) {
                    let b = {
                        value: [key, key2],
                        label: `${handicap[key2]}${handicap[key]}`
                    }
                    a.push(b)
                }
            });
        });

        state.matchDetail.tabs = a
        changeDetailactivetab(state.matchDetail.activetab)
        state.matchdetailIntervalId = setInterval(() => getmatchdetail(state.matchDetail.primaryData), 3000)

    }

    const clickblack = () => {
        state.matchDetail.show = false
        state.matchDetail.activetab = [
            "odds_data",
            "full"
        ]
        state.matchDetail.primaryData = {}
        state.matchDetail.data = {}
        state.matchDetail.datas = {}

        getmatch(false)
    }

    const changeordertype = (type) => {
        state.order.activetype = type
        getorderdata()
    }

    const getorderdata = () => {
        if (state.order.data.new_order_place_task_objs && state.order.data.live_order_place_task_objs) {
            if (state.order.activetype == 0) {
                state.order.activeorderdata = state.order.data.new_order_place_task_objs
            } else if (state.order.activetype == 1) {
                state.order.activeorderdata = state.order.data.live_order_place_task_objs
            } else if (state.order.activetype == 2) {
                state.order.activeorderdata = state.order.data.error_order_place_task_objs
            }
        }

    }

    const cancelOrder = (data) => {
        ElMessageBox.confirm(
            languageJson.value.message.isCancelOrder,
            languageJson.value.message.tips,
            {
                confirmButtonText: languageJson.value.message.confirm,
                cancelButtonText: languageJson.value.message.close,
                type: 'warning',
            }
        )
            .then(() => {
                http.post("/order/cancel_order_task", data).then((res) => {
                    ElMessage({
                        type: 'success',
                        message: languageJson.value.message.canceSuccess,
                    })
                })

            })
            .catch(() => {
            })


    }

    onMounted(async () => {
        initData()
    })

    onUnmounted(() => {
        clearInterval(state.matchlistIntervalId)
        clearInterval(state.matchdetailIntervalId)
    })


    async function initData() {
        state.activematchtabs = 'all'
        state.match = {
            loading: false,
            data: [],
            page: 1,
            page_size: 10,
            total: 0
        }
        getallleague()
        getmatchcount()
        getorderdata()
        getmatch(true)
    }


    return {
        state,

        changeSport,
        changeactivematchtabs,
        changeactiveleague,
        changeactiveleague2,
        clickmatch,
        openOrderDialog,
        changeDetailactivetab,
        clickblack,
        clickallleague,
        changeordertype,
        getorderdata,
        cancelOrder

    }
}
